/**
 * @license j2w.core.js
 * Defines the top level j2w object.
 *
 * Jobs2Web, INC CONFIDENTIAL
 * ------------------
 * Copyright 2003-2012 Jobs2Web, Inc
 * All Rights Reserved.
 * NOTICE: All information contained herein is, and remain the property of
 * Jobs2web, Inc and its suppliers, if any. The intellectual and
 * technical concepts contained herein are proprietary to Jobs2Web, Inc
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material is
 * strictly forbidden unless prior written permission is obtained from
 * Jobs2Web, Inc.
 */

var j2w = (function () {
    "use strict";

    // *** PRIVATE ************************************************************

    var _args = {},
        _bHasBeenInitted = false,
        _RE = {
            emailregex    : "^[\'_a-zA-Z0-9-]+(\\.[\'_a-zA-Z0-9-]+)*(\\+[\'_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.(([a-zA-Z]{2,4})|([a-zA-Z]{6}))$",
            passwordregex : "^(?=.{6,20}$)(?!.*(.)\\1{3})((?=.*[\\d])(?=.*[A-Za-z])|(?=.*[^\\w\\d\\s])(?=.*[A-Za-z])).*"
        },

        // *** METHODS

        _init = function (args) {
            if (!_bHasBeenInitted) {
                _args = args;

                return (_bHasBeenInitted = true);
            } else {
                return false;
            }
        },

        _get = function (needle, haystack) {
            if (needle && haystack) {
                if (haystack.hasOwnProperty(needle)) {
                    return haystack[needle];
                } else {
                    return undefined;
                }
            } else {
                return haystack;
            }
        };

    // *** PUBLIC *************************************************************

    return {
        applyID : null,
        applyInProgress : false,
        xhrAborted : false,
        xhrRequest : '',

        init : function (args) {
            return _init(args);
        },

        // *** NAMESPACED DEFAULT COLLECTIONS *********************************

        // *** Args - Initialization Arguments ********************************

        Args : {
            get : function (argName, haystack) {
                if (!haystack) {
                    haystack = _args;
                }

                return _get(argName, haystack);
            }
        },

        // *** Navigation - Related to Navigation Around the Site *************

        Navigation : {
            setReturnURL : function (url, callback) {
                $.ajax({
                    type     : 'GET',
                    url      : '/services/navigation/setredirect/',
                    data     : { url : url },
                    dataType : 'json',
                    complete: function(data) {
                        if (typeof callback === 'function') {
                            callback();
                        }
                    }
                });
            }
        },

        // *** RE - Regular Expressions ***************************************

        RE : {
            getEmailRegex : function () {
                return _RE.emailregex;
            },

            getPasswordRegex : function () {
                return _RE.passwordregex;
            }
        },

        // *** Validation - Validation ****************************************

        Validation : {
            isEmail : function (emailAddress) {
                var regex = new RegExp(_RE.emailregex);

                return regex.test(emailAddress);
            },
            isInteger : function (value) {
                var reg = /^\d+$/; // Only numbers

                return reg.test(value) && !isNaN(parseFloat(value)) && isFinite(value);
            },
            isPassword : function (password) {
                var regex = new RegExp(_RE.passwordregex);

                return regex.test(password);
            }
        },

        // *** Util - Miscellaneous Utility ***********************************

        Util : {
            // eventPreventer()
            // Prevents the default event, if the event passed in is a real event.
            eventPreventer : function (event) {
                if (typeof event.target === 'object' && event.target) {
                    event.preventDefault();
                }
            },

            // getParameterByName
            // Gets a URL variable by name, or null if it doesn't exist.
            getParameterByName : function (name) {
                var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);

                return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
            },

            // hasjQuery
            // Indicates if jQuery is available.
            hasjQuery : function () {
                return typeof jQuery === 'function' ? true : false;
            },

            // logout()
            // Logs the user out.
            logout : function (callback) {
                $.ajax({
                    type     : 'GET',
                    url      : '/services/security/logout',
                    dataType : 'json',
                    error: function (result) {

                    },
                    success: function (result) {
                        if (typeof callback === 'function') {
                            callback(result);
                        }
                    }
                });
            },

            // needToSwitchToSSL()
            // Returns {true|false} indicating if a switch to HTTPS protocol is necessary.
            needToSwitchToSSL : function () {
                var pageUsingHTTPS = 'https:' === document.location.protocol ? 1 : -1;

                return pageUsingHTTPS === -1 && j2w.Args.get('useSSL') === true;
            },

            // networkMap()
            // Maps a short social network name to its long version.
            networkMap : function (shortName) {
                switch(shortName) {
                    case 'li':
                        return 'linkedin';
                    break;
                    case 'fb':
                        return 'facebook';
                    break;
                    case 'gp':
                        return 'googleplus';
                    break;
                    case 'tw':
                        return 'twitter';
                    break;
                    default:
                        return '';
                    break;
                }
            },

            // resetPassword()
            // Sends an e-mail to the specified user with a link to reset their password.
            resetPassword : function (email, callback) {
                $.ajax({
                    type     : 'GET',
                    url      : '/services/security/getpassword',
                    data     : { email : email },
                    dataType : 'json',
                    error: function (result) {

                    },
                    success: function (result) {
                        if (typeof callback === 'function') {
                            callback(result);
                        }
                    }
                });
            }
        }

        // *** OTHER METHODS **************************************************

    };
}());

// Other non-namespaced, site-wide functionality.

String.prototype.unescapeHTML = function () {
    "use strict";

    return j2w.Util.hasjQuery() ? $('<div>' + this + '</div>').html() : this.toString();
};

String.prototype.format = function () {
    "use strict";

    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }

    return s;
};